package com.jiutong.meipengdai.ui.activitys;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseActivity;
import com.jiutong.meipengdai.base.CommonAdapter;
import com.jiutong.meipengdai.base.ViewHolder;
import com.jiutong.meipengdai.entity.EvaluateListRespond;
import com.jiutong.meipengdai.entity.EvaluateRecordBean;
import com.jiutong.meipengdai.http.model.interfaces.CheckLoginInterface;
import com.jiutong.meipengdai.http.model.requests.HousessInfoRequest;
import com.jiutong.meipengdai.http.present.HousessInfoPresent;
import com.jiutong.meipengdai.http.subscribers.ProgressSubscriber;
import com.jiutong.meipengdai.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipengdai.utils.DensityUtil;
import com.jiutong.meipengdai.utils.NumUilt;
import com.jiutong.meipengdai.views.FlowLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 评估记录
 * Created by suxi on 2017/6/2.
 */

@CheckLoginInterface
public class EvaluateRecordActivity extends BaseActivity {

    public static int RECORD_RESULT_CORD = 10000;
    @Bind(R.id.rl_back)
    RelativeLayout rl_back;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_options)
    TextView tv_options;
    @Bind(R.id.line)
    View line;
    @Bind(R.id.tv_can_loan_money)
    TextView tv_can_loan_money;
    @Bind(R.id.common_listview)
    ListView commonListview;
    @Bind(R.id.tv_evaluate_loan)
    TextView tv_evaluate_loan;
    @Bind(R.id.ll_top)
    LinearLayout ll_top;
    @Bind(R.id.tv_house_list_yuan)
    TextView tv_house_list_yuan;
    @Bind(R.id.tv_no_reply)
    TextView tvNoReply;
    @Bind(R.id.left_line)
    View leftLine;
    @Bind(R.id.rl_no_reply)
    RelativeLayout rlNoReply;
    @Bind(R.id.tv_has_reply)
    TextView tvHasReply;
    @Bind(R.id.right_line)
    View rightLine;
    @Bind(R.id.rl_has_reply)
    RelativeLayout rlHasReply;
    private SubscriberOnNextListener onNextListener;
    private HashMap<String, Object> fieldsMap;
    private ProgressSubscriber progressSubscriber;
    private HousessInfoRequest request;
    private double loanSumAmount;
    private double noLoanSumAmount;
    private ArrayList<EvaluateRecordBean> evaluateRecordApplyList = new ArrayList<>();  //已申请
    private ArrayList<EvaluateRecordBean> evaluateRecordNoApplyList = new ArrayList<>();  //未申请
    private EvaluateRecordListAdapter evaluateRecordListAdapter;
    private List<EvaluateRecordBean> dateList = new ArrayList<>();
    private boolean isFromLoanFragment;
    private int currenTab = R.id.rl_no_reply;

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_evaluate_record;
    }

    private void initHouse() {
        if (request == null) {
            request = new HousessInfoRequest();
        }
        onNextListener = new SubscriberOnNextListener<EvaluateListRespond>() {

            @Override
            public void onNext(EvaluateListRespond subjects) {
                if (subjects.getResCode().equals("1110")) {

                } else if (subjects.getResCode().equals("200")) {
                    evaluateRecordNoApplyList.clear();
                    evaluateRecordApplyList.clear();
                    dateList.clear();
                    loanSumAmount = subjects.getData().getLoanSumAmount();
                    noLoanSumAmount = subjects.getData().getNoLoanSumAmount();

                    List<EvaluateListRespond.DataBean.AssessmentInfosNoLoanBean> assessmentInfosNoLoan = subjects.getData().getAssessmentInfosNoLoan();

                    if (assessmentInfosNoLoan != null && assessmentInfosNoLoan.size() > 0) {
                        for (int i = 0; i < assessmentInfosNoLoan.size(); i++) {
                            EvaluateRecordBean evaluateRecordBean = new EvaluateRecordBean();
                            evaluateRecordBean.setId(assessmentInfosNoLoan.get(i).getId());
                            evaluateRecordBean.setHouseCity(assessmentInfosNoLoan.get(i).getHouseCity());
                            evaluateRecordBean.setHouseArea(assessmentInfosNoLoan.get(i).getHouseArea());
                            evaluateRecordBean.setHouseOrientate(assessmentInfosNoLoan.get(i).getHouseOrientate());
                            evaluateRecordBean.setIsLoan(assessmentInfosNoLoan.get(i).getIsLoan());
                            evaluateRecordBean.setTotalAmount(assessmentInfosNoLoan.get(i).getTotalAmount());
                            evaluateRecordBean.setHouseFloor(assessmentInfosNoLoan.get(i).getHouseFloor());
                            evaluateRecordBean.setAssessmentPdfUrl(assessmentInfosNoLoan.get(i).getAssessmentPdfUrl());
                            evaluateRecordBean.setHouseSize(assessmentInfosNoLoan.get(i).getHouseSize());
                            evaluateRecordBean.setResidentialArea(assessmentInfosNoLoan.get(i).getResidentialArea());
                            evaluateRecordBean.setRate(assessmentInfosNoLoan.get(i).getRate());
                            evaluateRecordBean.setPercentage(assessmentInfosNoLoan.get(i).getPercentage());
                            evaluateRecordBean.setTotalFloor(assessmentInfosNoLoan.get(i).getTotalFloor());
                            evaluateRecordNoApplyList.add(evaluateRecordBean);
                        }
                    }
                    List<EvaluateListRespond.DataBean.AssessmentInfosLoanBean> assessmentInfosLoan = subjects.getData().getAssessmentInfosLoan();

                    if (assessmentInfosLoan != null && assessmentInfosLoan.size() > 0) {
                        for (int i = 0; i < assessmentInfosLoan.size(); i++) {
                            EvaluateRecordBean evaluateRecordBean = new EvaluateRecordBean();
                            evaluateRecordBean.setId(assessmentInfosLoan.get(i).getId());
                            evaluateRecordBean.setHouseCity(assessmentInfosLoan.get(i).getHouseCity());
                            evaluateRecordBean.setHouseArea(assessmentInfosLoan.get(i).getHouseArea());
                            evaluateRecordBean.setHouseOrientate(assessmentInfosLoan.get(i).getHouseOrientate());
                            evaluateRecordBean.setIsLoan(assessmentInfosLoan.get(i).getIsLoan());
                            evaluateRecordBean.setTotalAmount(assessmentInfosLoan.get(i).getTotalAmount());
                            evaluateRecordBean.setHouseFloor(assessmentInfosLoan.get(i).getHouseFloor());
                            evaluateRecordBean.setAssessmentPdfUrl(assessmentInfosLoan.get(i).getAssessmentPdfUrl());
                            evaluateRecordBean.setHouseSize(assessmentInfosLoan.get(i).getHouseSize());
                            evaluateRecordBean.setResidentialArea(assessmentInfosLoan.get(i).getResidentialArea());
                            evaluateRecordBean.setRate(assessmentInfosLoan.get(i).getRate());
                            evaluateRecordBean.setPercentage(assessmentInfosLoan.get(i).getPercentage());
                            evaluateRecordBean.setTotalFloor(assessmentInfosLoan.get(i).getTotalFloor());
                            evaluateRecordApplyList.add(evaluateRecordBean);
                        }
                    }
                    dateList.addAll(evaluateRecordNoApplyList);
                    noLoanSumAmount = noLoanSumAmount + loanSumAmount;
                    evaluateRecordListAdapter = new EvaluateRecordListAdapter(mContext, dateList, R.layout.view_evaluate_record);
                    commonListview.setAdapter(evaluateRecordListAdapter);
                    tv_can_loan_money.setText(noLoanSumAmount > 10000 ? NumUilt.formatDouble(noLoanSumAmount / 10000) + "万" : noLoanSumAmount + "");
                }
            }

            @Override
            public void onError(Throwable e) {

            }
        };
        fieldsMap = new HashMap<>();
        progressSubscriber = new ProgressSubscriber(onNextListener, mContext);

        request.getEvaluateList(progressSubscriber, fieldsMap);

    }

    @Override
    protected void initDate(Bundle savedInstanceState) {
        super.initDate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            isFromLoanFragment = extras.getBoolean("isFromLoanFragment");
        }
    }

    @Override
    protected void initView() {
        super.initView();
        ButterKnife.bind(this);
        tvTitle.setText("评估记录");

        commonListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                EvaluateRecordBean evaluateRecordBean = dateList.get(position);
                Bundle bundle = new Bundle();

                if (!isFromLoanFragment || currenTab == R.id.rl_has_reply) {
                    bundle.putString("houseId", evaluateRecordBean.getId());
                    bundle.putBoolean("from_record_activity", true);

                    if(currenTab == R.id.rl_has_reply){
                        bundle.putBoolean("hasApply", true);
                    }else{
                        bundle.putBoolean("hasApply", false);
                    }
                    openActivity(EvaluateResultActivity.class, bundle);
                } else {
                    Intent intent = new Intent();
                    bundle.putParcelable("recordInfo", evaluateRecordBean);
                    intent.putExtras(bundle);
                    setResult(RECORD_RESULT_CORD, intent);
                    finish();
                }
            }
        });

        initHouse();

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnClick({R.id.rl_back, R.id.tv_evaluate_loan, R.id.rl_no_reply, R.id.rl_has_reply})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_evaluate_loan:
                openActivity(LoanApplyActivity.class);
                finish();
                break;
            case R.id.rl_no_reply:
                currenTab = R.id.rl_no_reply;
                dateList.clear();
                dateList.addAll(evaluateRecordNoApplyList);
                tv_evaluate_loan.setVisibility(View.VISIBLE);
                tvNoReply.setTextColor(getResources().getColor(R.color.orange));
                leftLine.setBackgroundColor(getResources().getColor(R.color.orange));
                tvHasReply.setTextColor(getResources().getColor(R.color.gray));
                rightLine.setBackgroundColor(getResources().getColor(R.color.white));

                if (evaluateRecordListAdapter != null)
                    evaluateRecordListAdapter.notifyDataSetChanged();

//                tv_can_loan_money.setText(noLoanSumAmount >= 10000 ? NumUilt.formatDouble(noLoanSumAmount / 10000) + "万" : noLoanSumAmount + "");
                break;

            case R.id.rl_has_reply:
                currenTab = R.id.rl_has_reply;
                dateList.clear();
                dateList.addAll(evaluateRecordApplyList);
                tv_evaluate_loan.setVisibility(View.GONE);
                tvHasReply.setTextColor(getResources().getColor(R.color.orange));
                rightLine.setBackgroundColor(getResources().getColor(R.color.orange));
                tvNoReply.setTextColor(getResources().getColor(R.color.gray));
                leftLine.setBackgroundColor(getResources().getColor(R.color.white));

                if (evaluateRecordListAdapter != null)
                    evaluateRecordListAdapter.notifyDataSetChanged();

//                tv_can_loan_money.setText(loanSumAmount >= 10000 ? NumUilt.formatDouble(loanSumAmount / 10000) + "万" : loanSumAmount + "");
                break;
        }
    }

    //流式布局
    public void addView(FlowLayout flowLayout, String text, int resourceId, int color) {
        int ranHeight = DensityUtil.dip2px(mContext, 25);
        int ranWidth = DensityUtil.dip2px(mContext, 55);
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ranWidth, ranHeight);
        lp.setMargins(DensityUtil.dip2px(mContext, 0), 0, DensityUtil.dip2px(mContext, 10), 0);
        TextView textView = (TextView) View.inflate(mContext, R.layout.simple_text, null);
        textView.setText(text);
        textView.setBackgroundResource(resourceId);
        textView.setTextColor(color);
        flowLayout.addView(textView, lp);
    }

    public class EvaluateRecordListAdapter extends CommonAdapter<EvaluateRecordBean> {

        public EvaluateRecordListAdapter(Context context, List<EvaluateRecordBean> listDatas, int layoutId) {
            super(context, listDatas, layoutId);
        }

        @Override
        protected void fillData(ViewHolder holder, int position) {

            TextView tvEvaluate = holder.getView(R.id.tv_evaluate_id);
            TextView tvPrice = holder.getView(R.id.tv_price);
            TextView tvHouseName = holder.getView(R.id.tv_house_name);
            FlowLayout flowLayout = holder.getView(R.id.flowlayout);
            flowLayout.removeAllViews();

            tvEvaluate.setText(listDatas.get(position).getId());
            String totalAmount = listDatas.get(position).getTotalAmount();
            float totaoAmount = Float.parseFloat(totalAmount);
            tvPrice.setText(totaoAmount > 10000 ? NumUilt.formatFloat(totaoAmount / 10000) + "万" : NumUilt.formatFloat(totaoAmount) + "");
            tvHouseName.setText(listDatas.get(position).getHouseCity() + listDatas.get(position).getHouseArea() + listDatas.get(position).getResidentialArea());

            addView(flowLayout, listDatas.get(position).getHouseSize() + "㎡", R.drawable.shape_light_blue_ring, getResources().getColor(R.color.light_blue));
            addView(flowLayout, listDatas.get(position).getHouseFloor()+" / "+listDatas.get(position).getTotalFloor(), R.drawable.shape_light_purple_ring, getResources().getColor(R.color.light_purple));
            addView(flowLayout, listDatas.get(position).getHouseOrientate(), R.drawable.shape_light_green_ring, getResources().getColor(R.color.light_green));
        }
    }

}
